/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multisistema.objetos;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import multisistema.db.MySQL;

/**
 *
 * @author EDONALDO01
 */
public class Usuario {

    private int id;
    private String nombre;
    private String clave;
    private Permiso permiso1;

    public Usuario() {
        this.id = -1;
        this.nombre = "";
        this.clave = "";
        this.permiso1 = null;
    }
    
    public Usuario(int id) {
        this.id = id;
        getById();
    }
    
    private void getById() {
        Statement stmt = null;
        ResultSet rs = null;
        MySQL mydb = new MySQL();
        Connection conn = mydb.getConn();
        try {
            stmt = conn.createStatement();
            if (stmt.execute("SELECT * FROM `tbl_usuario` WHERE `id_usuario` = " + this.getId())) {
                rs = stmt.getResultSet();
            }
            if (rs.next()) {
                this.setId(rs.getInt("id_usuario"));
                this.setNombre(rs.getString("nombre_usuario"));
                this.setClave(rs.getString("clave"));
                this.setPermiso1(new Permiso(rs.getInt("id_permiso")));
            } else {
                this.setId(-1);
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) {
                }
                rs = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) {
                }
                stmt = null;
            }
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * @return the nombre
     */
    public String getNombre() {
        return nombre;
    }

    /**
     * @param nombre the nombre to set
     */
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    /**
     * @return the clave
     */
    public String getClave() {
        return clave;
    }

    /**
     * @param clave the clave to set
     */
    public void setClave(String clave) {
        this.clave = MD5(clave);
    }

    /**
     * @return the permiso1
     */
    public Permiso getPermiso1() {
        return permiso1;
    }

    /**
     * @param permiso1 the permiso1 to set
     */
    public void setPermiso1(Permiso permiso1) {
        this.permiso1 = permiso1;
    }

    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

    public static List<Usuario> getUsuarios() {
        List<Usuario> lista = new ArrayList<Usuario>();
        Statement stmt = null;
        ResultSet rs = null;
        MySQL mydb = new MySQL();
        Connection conn = mydb.getConn();
        try {
            stmt = conn.createStatement();
            if (stmt.execute("SELECT * FROM `tbl_usuario` ")) {
                rs = stmt.getResultSet();
            }

            while (rs.next()) {
                Usuario usr = new Usuario();
                usr.setId(rs.getInt("id_usuario"));
                usr.setNombre(rs.getString("nombre_usuario"));
                usr.setClave(rs.getString("clave"));
                usr.setPermiso1(new Permiso(rs.getInt("id_permiso")));
                lista.add(usr);
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) {
                }
                rs = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) {
                }
                stmt = null;
            }
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        return lista;
    }

    public boolean Validar() {
        Statement stmt = null;
        ResultSet rs = null;
        MySQL mydb = new MySQL();
        Connection conn = mydb.getConn();
        try {
            stmt = conn.createStatement();
            if (stmt.execute("SELECT * FROM `tbl_usuario` WHERE `nombre_usuario` = '" + this.getNombre() + "'")) {
                rs = stmt.getResultSet();
            }
            if (rs.next()) {
                if (this.getClave().toLowerCase().equals(rs.getString("clave"))) {
                    this.setId(rs.getInt("id_usuario"));
                    this.setPermiso1(new Permiso(rs.getInt("id_permiso")));
                    return true;
                }
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) {
                }
                rs = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) {
                }
                stmt = null;
            }
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        return false;
    }

    public void eliminar() {
        Statement stmt = null;
        ResultSet rs = null;
        MySQL mydb = new MySQL();
        Connection conn = mydb.getConn();
        try {
            stmt = conn.createStatement();
            stmt.executeUpdate("DELETE FROM `multisistema`.`tbl_usuario` WHERE `tbl_usuario`.`id_usuario` = " + this.getId() + ";");
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }
        }
    }

    public void agregar() {
        Statement stmt = null;
        ResultSet rs = null;
        MySQL mydb = new MySQL();
        Connection conn = mydb.getConn();
        try {
            stmt = conn.createStatement();
            stmt.executeUpdate("INSERT INTO `multisistema`.`tbl_usuario` "
                    + "(`id_usuario`, `nombre_usuario`, `clave`, `id_permiso`)"
                    + " VALUES (NULL, '" + this.getNombre() + "', '" + this.getClave() + "', '" + this.getPermiso1().getId()
                    + "');");

            rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
            if (rs.next()) {
                this.setId(rs.getInt(1));
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }
        }
    }
    
    public void modificar() {
        Statement stmt = null;
        ResultSet rs = null;
        MySQL mydb = new MySQL();
        Connection conn = mydb.getConn();
        try {
            stmt = conn.createStatement();
            stmt.executeUpdate("UPDATE `multisistema`.`tbl_usuario` SET "
                    + "`nombre_usuario` = '" + this.getNombre()
                    + "', `clave` = '" + this.getClave()
                    + "', `id_permiso` = '" + this.getPermiso1().getId()
                    + "' WHERE `id_usuario` = '" + this.getId()
                    + "';");

            rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
            if (rs.next()) {
                this.setId(rs.getInt(1));
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }
        }
    }
}
